package com.winchain.provider.expiration.cmd;

import com.shell.framework.command.CommandContext;
import com.shell.framework.command.ICommand;
import com.winchain.chainbill.bill.base.po.CbRec;
import com.winchain.chainbill.bill.base.service.CbRecService;
import com.winchain.provider.expiration.po.CbDebit;
import com.winchain.provider.expiration.rx.BillExpirationEvent;
import com.winchain.provider.expiration.service.BillExpQueryService;
import com.winchain.provider.expiration.service.BillExpStateService;
import com.winchain.provider.expiration.service.CbCreditService;
import com.winchain.provider.expiration.service.CbDebitService;
import java.util.Collection;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
public class BillExpChdSettlCmd implements ICommand<BillExpirationEvent> {
	@Autowired
	private CbRecService cbRecService;
	@Autowired
	protected BillExpQueryService billExpQueryService;
	@Autowired
	private BillExpStateService billExpStateService;
	@Autowired
	private CbDebitService cbDebitService;
	@Autowired
	private CbCreditService cbCreditService;

	public boolean execute(CommandContext<BillExpirationEvent> context) throws Exception {
		BillExpirationEvent event = (BillExpirationEvent) context.getSource();
		String expDate = event.getDate();
		boolean pm = event.isPm();
		String grpId = event.getGrpId();

		List<CbRec> children = this.billExpQueryService.selectExpChdBills(expDate, grpId);
		for (CbRec bill : children) {
			delayProcess(bill, expDate, pm);
		}
		return false;
	}

	protected void delayProcess(CbRec bill, String expDate, boolean pm) {
		if (this.billExpStateService.rollback(bill)) {
			bill = (CbRec) this.cbRecService.selectByKey(bill.getBillId());
		}
		String billState = bill.getBillState();
		if (("S005".equals(billState)) || ("S012".equals(billState)) || ("S011".equals(billState))
				|| ("S035".equals(billState))) {
			CbDebit debit = this.cbDebitService.saveBillDebit(bill, expDate, true);

			this.cbCreditService.saveBillCredit(debit, bill, expDate);
		} else {
			Collection<CbRec> children = this.billExpQueryService.getExpChdBills(expDate, bill.getBillId());
			if ((children != null) && (children.size() > 0)) {
				for (CbRec child : children) {
					if (this.billExpStateService.rollback(child, pm)) {
						child = (CbRec) this.cbRecService.selectByKey(child.getBillId());
					}
					CbRec leafBill = this.cbRecService.selectLeafBills(bill.getBillId(), child.getBillId());
					if (leafBill != null) {
						CbDebit debit = this.cbDebitService.saveBillDebit(child, expDate, true);

						this.cbCreditService.saveBillCredit(debit, child, expDate);
					}
					this.billExpStateService.expire(child);
				}
			}
		}
		this.billExpStateService.expire(bill);
	}
}
